<?php

namespace Xin\LaravelFortify\Lock;

use Illuminate\Contracts\Cache\LockTimeoutException;

trait WithLock
{
	/**
	 * @var Lock
	 */
	protected $lock = null;

	/**
	 * @var string
	 */
	protected $lockPrefix = '';

	/**
	 * 使用固定时长锁
	 * @param callable $closure
	 * @param string $action
	 * @param int $ttl
	 * @return mixed
	 * @throws LockTimeoutException
	 */
	public function fixedLock(callable $closure, $action, $ttl = 5)
	{
		return $this->lock()->fixedLock($closure, $action, $ttl);
	}

	/**
	 * @return Lock
	 */
	public function lock()
	{
		if ($this->lock === null) {
			$this->lock = new Lock($this->lockPrefix);
		}

		return $this->lock;
	}

	/**
	 * 使用动态时长锁
	 * @param callable $closure
	 * @param string $action
	 * @param int $ttl
	 * @return mixed
	 * @throws LockTimeoutException
	 */
	public function dynamicLock(callable $closure, $action, $ttl = 5)
	{
		return $this->lock()->dynamicLock($closure, $action, $ttl);
	}

	/**
	 * 使用阻塞式锁
	 * @param callable $closure
	 * @param string $action
	 * @param int $ttl
	 * @param int $block
	 * @return mixed
	 * @throws LockTimeoutException
	 */
	public function blockLock(callable $closure, $action, $ttl = 5, $block = 5)
	{
		return $this->lock()->blockLock($closure, $action, $ttl, $block);
	}
}
